package com.ainge.easystudy.thread;

import java.util.Optional;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: Ainge
 * @Time: 2021/6/12 14:12
 */
public class ProducerConsumerBlockingQueueDemo {

    public static void main(String[] args) {
        // 创建资源类
        final MyResource<Integer> resource = new MyResource<>(new ArrayBlockingQueue<>(10));
        new Thread(() -> {
            try {
                for (int i = 0; i < 10000; i++) {
                    resource.producer(i);
                }
            } catch (Exception e) {
            }
        }, "producer").start();

        new Thread(() -> {
            try {
                resource.consumer();
            } catch (Exception e) {
            }
        }, "consumer").start();

    }

}

// 资源类
class MyResource<T> {
    // 阻塞队列
    private final BlockingQueue<T> queue;

    public MyResource(BlockingQueue<T> queue) {
        this.queue = queue;
        System.out.println(Optional.ofNullable(queue).map(q -> q.getClass().getName()).orElse(""));
    }

    public void producer(T data) throws Exception {
        boolean returnVal = queue.offer(data, 2L, TimeUnit.SECONDS);
        System.out.println(String.format("生产数据（%s）结果为%s", data, returnVal));
    }

    public void consumer() throws Exception {
        while (true) {
            T data = queue.poll(2L, TimeUnit.SECONDS);
            if (data == null) {
                System.out.println("获取不到数据，表示生产已经结束了");
                break;
            }
            System.out.println("消费数据成功");
        }
    }


}